import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.sql.mysql_refund import insert_refund, insert_refund_order, insert_refund_logistics
from app.utils.signUtil import sign_util
import httpx
import asyncio
from app.utils.time_util import get_three_days_ago, get_current_time

async def task_save_refund():
    try:
        async with httpx.AsyncClient() as client:
            # 构建请求参数，包含必要的 sid 参数
            param = sign_util(get_three_days_ago(), get_current_time(), "0", "100")
            url = 'https://api.wangdian.cn/openapi2/vip_api_refund_query.php'
            
            response = await client.get(
                url=url,
                params=param,
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            
            if "refund_list" not in data:
                raise ValueError(f"API返回格式异常: {data}")
                
            loop = asyncio.get_event_loop()
            for refund in data["refund_list"]:
                try:
                    # 保存退款主单信息
                    await loop.run_in_executor(None, insert_refund, refund)
                    
                    # 处理退款商品明细
                    refund_orders = refund.get("order_list", [])
                    for order in refund_orders:
                        await loop.run_in_executor(None, insert_refund_order, order)
                        
                except Exception as e:
                    print(f"处理退款数据时出错 (退款单号可能为 {refund.get('refund_no')}): {e}")
                    
    except Exception as e:
        print(f"保存退款数据时出错: {e}")
        raise 

async def task_save_refund_logistics():
    try:
        async with httpx.AsyncClient() as client:
            param = sign_util(get_three_days_ago(), get_current_time(), "0", "100")
            url = 'https://api.wangdian.cn/openapi2/stock_refund_logistics_query.php'
            
            response = await client.get(
                url=url,
                params=param,
                timeout=10
            )
            response.raise_for_status()
            data = response.json()
            
            if "logistics_list" not in data:
                raise ValueError(f"API返回格式异常: {data}")
                
            loop = asyncio.get_event_loop()
            for logistics in data["logistics_list"]:
                try:
                    await loop.run_in_executor(None, insert_refund_logistics, logistics)
                except Exception as e:
                    print(f"处理退货物流数据时出错 (退货单号可能为 {logistics.get('refund_no')}): {e}")
                    
    except Exception as e:
        print(f"保存退货物流数据时出错: {e}")
        raise 